package Hot100;

import DMSXL._2023Before.ListNode_.ListNode;

public class addTwoNumbers {
    public static void main(String[] args) {
        int[] listA = {9,9,9,9,9,9,9};
        int[] listB = {9,9,9,9};
        ListNode headA = new ListNode(listA[0]);
        ListNode headB = new ListNode(listB[0]);
        ListNode preA = headA;
        ListNode preB = headB;
        for (int i = 1; i < listA.length; i++) {
            ListNode temp = new ListNode(listA[i]);
            preA.next = temp;
            preA = preA.next;
        }
        for (int i = 1; i < listB.length; i++) {
            ListNode temp = new ListNode(listB[i]);
            preB.next = temp;
            preB = preB.next;
        }
        ListNode ans= addTwoNumbers(headA,headB);
        while(ans != null){
            System.out.println(ans.val);
            ans = ans.next;
        }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode();
        ListNode prev = pre;
        int extra = 0;
        int value = 0;
        while (l1 != null && l2 != null){
            value = l1.val + l2.val + extra;
            if(value >= 10){
                extra = 1;
                value = value - 10;
            }else {
                extra = 0;
            }
            ListNode temp = new ListNode(value);
            pre.next = temp;
            pre = pre.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1 != null){
            value = l1.val + extra;
            if(value >= 10){
                extra = 1;
                value = value - 10;
            }else {
                extra = 0;
            }
            ListNode temp = new ListNode(value);
            pre.next = temp;
            pre = pre.next;
            l1 = l1.next;

        }
        while(l2 != null){
            value = l2.val + extra;
            if(value >= 10){
                extra = 1;
                value = value - 10;
            }else {
                extra = 0;
            }
            ListNode temp = new ListNode(value);
            pre.next = temp;
            pre = pre.next;
            l2 = l2.next;
        }
        if(extra == 1){
            ListNode temp = new ListNode(extra);
            pre.next = temp;
            pre = pre.next;
        }
        return prev.next;
    }
}
